import React, { useState, useEffect } from 'react'
import axios from 'axios'
import { Descriptions, Tooltip } from 'antd'
import { LikeOutlined, SendOutlined } from '@ant-design/icons'
import moment from 'moment'
import './Detail.module.css'

export default function NewsPreview(props) {
    const [newsInfo, setNewsInfo] = useState()
    // 获取数据，顺便更新浏览量
    useEffect(() => {
        axios.get(`/news/${props.match.params.id}?_expand=category&_expand=role`).then(res => {
            // console.log(res);
            setNewsInfo({ ...res.data, view: res.data.view + 1 })
            // 同步后端
            return res.data
        }).then(res => {
            axios.patch(`/news/${props.match.params.id}`, {
                view: res.view + 1
            })
        })
    }, [props.match.params.id])

    // 点赞
    const handleLike = () => {
        setNewsInfo({
            ...newsInfo,
            star: newsInfo.star + 1
        })
        axios.patch(`/news/${props.match.params.id}`, {
            star: newsInfo.star + 1
        })
    }

    return (
        <div style={{ width: '90%', margin: '50px auto' }}>
            {newsInfo && <div>
                <div>
                    <Tooltip placement="top" title="返回">
                        <SendOutlined onClick={() => { window.history.back() }} rotate={180} style={{ cursor: "pointer", fontSize: "35px", color: "#007acc", marginRight: "20px" }} />
                    </Tooltip>
                    <Tooltip placement="top" title="点赞">
                        <LikeOutlined onClick={() => handleLike()} style={{ cursor: "pointer", fontSize: "35px", color: "#2ba245" }} />
                    </Tooltip>
                    <Descriptions bordered={true} title={newsInfo.title} column={4} >
                        <Descriptions.Item label="创建者">{newsInfo.author}</Descriptions.Item>
                        <Descriptions.Item label="所属分类">{newsInfo.category.title}</Descriptions.Item>
                        <Descriptions.Item label="发布时间">{newsInfo.publishTime ? moment(newsInfo.publishTime).format("YYYY/MM/DD HH:mm:ss") : "-"}</Descriptions.Item>
                        <Descriptions.Item label="区域">{newsInfo.region}</Descriptions.Item>
                        <Descriptions.Item label="访问数量">{newsInfo.view}</Descriptions.Item>
                        <Descriptions.Item label="点赞数量">{newsInfo.star}</Descriptions.Item>
                        <Descriptions.Item label="评论数量">0</Descriptions.Item>
                    </Descriptions>

                    <div dangerouslySetInnerHTML={{
                        __html: newsInfo.content
                    }} style={{
                        margin: "0 24px",
                    }}>
                    </div>
                </div>
            </div>
            }
        </div>
    )
}
